<?php


namespace app\api\service;


use app\exception\TokenException;
use think\Exception;
use think\facade\Cache;
use think\facade\Request;

class Token
{
    public static function generateToken(): string
    {
        // 32 个 令牌 组成一组随机字符串
        $randChars = getRandChar(32);
        //用三组字符串，进行 md5 加密
        $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
        // salt 盐
        $salt = config('secure.token_salt');
        return md5($randChars.$timestamp.$salt);
    }

    /**
     * @param $key
     *
     * @return mixed
     * @throws TokenException
     * @throws Exception
     */
    public static function getCurrentTokenVar($key){
        $token = Request::header('token');
        $vars = Cache::get($token);
        if(!$vars){
            throw new TokenException();
        }else{
            if(!is_array($vars)){
                $vars = json_decode($vars,true);
            }
            if(array_key_exists($key,$vars)){
                return $vars[$key];
            }else{
                throw new Exception('尝试获取token变量不存在');
            }
        }

    }

    /**
     * @return mixed
     * @throws Exception
     * @throws TokenException
     */
    public static function getCurrentID (){
        //token 获取uid
        try {
            return self::getCurrentTokenVar('uid');
        } catch (TokenException $e) {
            throw new TokenException();
        } catch (Exception $e) {
            throw new Exception('尝试获取token变量不存在');
        }
    }

    /**
     * @param $checkedUID
     * 检测UID 是否和 当前用户UID一致
     *
     * @return bool
     * @throws Exception
     */
    public static function isValidOperate($checkedUID): bool
    {
        if(!$checkedUID){
            throw new Exception("检查UID时必须传入一个被检查的UID");
        }
        $currentOperateUID = self::getCurrentID();
        return $checkedUID == $currentOperateUID;
    }
}